# 安装redis_py  pip install redis
# 只需记住：redis 包就是官方 redis-py

import redis

# 直接连接到redis
def get_connection():
    connection = redis.Redis(
        host='localhost',
        port=6379,
        db=1
    )
    return connection


# 使用连接池
def get_connection_by_pool():
    pool = redis.ConnectionPool(
        host='localhost',
        port=6379,
        db=1,
        max_connections=20
    )
    connection = redis.Redis(
        connection_pool=pool
    )
    return connection

# 关闭连接
def close_connection(conn):
    conn.close()



class BaseRedisConnection(object):
    def __init__(self):
        # 直连
        # self.conn = redis.Redis(
        #     host='localhost',
        #     port=6379,
        #     db=1,
        #     decode_responses=True
        # )
        # 连接池连接
        pool = redis.ConnectionPool(
            host='localhost',
            port=6379,
            db=1,
            max_connections=20,
            decode_responses=True
        )
        self.conn = redis.Redis(
            connection_pool=pool
        )

    def __del__(self):
        try:
            print('关闭连接池')
            self.conn.close()
        except Exception as e:
            print(e)


if __name__ == '__main__':
    connection = get_connection()
    connection.set('key','value')
    close_connection(connection)

    connection2 = get_connection_by_pool()
    result = connection2.set('key2','value2')
    print(result)
    close_connection(connection2)
    # connection2.close()